<template>
  <div class="exam_box" v-loading="loading">
    <div class="exam_addbtn">
      <el-button icon="plus" @click="openAddDialog()" type="primary">
        新增考试
      </el-button>
      <span style="margin-left: 12px">学期：</span>
      <el-select
        v-model="examPageParmas.semesterId"
        placeholder="请选择学期"
        clearable
        filterable
        @change="getExamInfoPage()"
      >
        <el-option
          v-for="item in semesterOptions"
          :key="item.id"
          :label="item.name"
          :value="item.id"
        />
      </el-select>
    </div>
    <el-table
      :data="examDatas"
      border
      :header-row-style="{ color: '#232324', fontWeight: 'bold' }"
    >
      <el-table-column
        align="center"
        type="index"
        :index="indexMethod"
        label="序号"
        width="80"
      />
      <el-table-column
        align="center"
        label="考试名称"
        min-width="120"
        prop="examName"
      />
      <el-table-column
        align="center"
        label="课程名称"
        min-width="120"
        prop="courseName"
      />
      <el-table-column
        align="center"
        label="老师"
        min-width="120"
        prop="teacherName"
      />
      <el-table-column
        align="center"
        label="考试时间"
        min-width="180"
        prop="examDate"
      />
      <el-table-column
        align="center"
        label="考试时长min"
        min-width="120"
        prop="duration"
      />
      <el-table-column
        align="center"
        label="考试地点"
        min-width="120"
        prop="location"
      />
      <el-table-column
        align="center"
        label="考试描述"
        min-width="180"
        prop="description"
      />
      <el-table-column
        align="center"
        label="创建时间"
        min-width="180"
        prop="createTime"
      />
      <el-table-column align="center" fixed="right" label="操作" width="300">
        <template #default="scope">
          <el-button
            type="primary"
            link
            icon="edit"
            @click="openEditDialog(scope.row)"
          >
            编辑
          </el-button>
          <el-popconfirm
            :icon="InfoFilled"
            icon-color="#626AEF"
            width="180"
            title="是否删除该考试?"
            @confirm="deleteExamById(scope.row.examId)"
          >
            <template #reference>
              <el-button type="primary" link icon="delete">删除</el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      style="margin-top: 12px"
      v-model:current-page="examPageParmas.pageNum"
      v-model:page-size="examPageParmas.pageSize"
      :page-sizes="[10, 20, 40]"
      :background="true"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />

    <el-dialog
      v-model="dialogFormVisible"
      :title="dialogTitle"
      style="min-width: 320px"
    >
      <el-form
        v-if="dialogFormVisible"
        ref="examForms"
        :inline="true"
        :model="examForm"
        :rules="rules"
        label-position="top"
        label-width="85px"
      >
        <el-form-item label="考试名称" prop="examName" style="width: 40%">
          <el-input v-model="examForm.examName" placeholder="请输入考试名称" />
        </el-form-item>
        <el-form-item label="课程ID" prop="courseId" style="width: 40%">
          <el-input v-model="examForm.courseId" placeholder="请输入课程ID" />
        </el-form-item>
        <el-form-item label="考试时间" prop="examDate" style="width: 40%">
          <el-date-picker
            v-model="examForm.examDate"
            type="datetime"
            value-format="YYYY-MM-DD hh:mm:ss"
            placeholder="请选择考试时间"
          />
        </el-form-item>
        <el-form-item label="考试时长" prop="duration" style="width: 40%">
          <el-input-number v-model="examForm.duration" :min="30" :max="180" />
        </el-form-item>
        <el-form-item label="考试地点" prop="location" style="width: 40%">
          <el-input v-model="examForm.location" placeholder="请输入考试地点" />
        </el-form-item>
        <el-form-item label="考试描述" prop="description" style="width: 40%">
          <el-input
            type="textarea"
            v-model="examForm.description"
            placeholder="请输入考试描述"
            :rows="4"
            show-word-limit
            :maxlength="100"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="formConfirm(examForms)">
            提交
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive } from 'vue'
import { ElMessage } from 'element-plus'
import { InfoFilled } from '@element-plus/icons-vue'
import type { FormInstance } from 'element-plus'
import {
  reqAddExam,
  reqDeleteExamById,
  reqGetAllExamByAdmin,
  reqUpdateExam,
} from '@/api/exam'
import { ExamPageQuery, ExamParams, ExamType } from '@/api/exam/type'
import { OptionType } from '@/api/user/type'
import { reqGetSemesterOption } from '@/api/semester'

onMounted(async () => {
  await getExamInfoPage()
  await getSemesterOption()
})

const dialogFormVisible = ref<boolean>(false)
const examPageParmas: ExamPageQuery = reactive({
  pageNum: 1,
  pageSize: 10,
})
const examDatas = ref<ExamType[]>()
const semesterOptions = ref<OptionType[]>([])
const total = ref(0)
const loading = ref(false)

const examForms = ref<FormInstance>()
let examForm: ExamParams = reactive({
  examId: 0,
  examName: '',
  courseId: 0,
  examDate: '',
  duration: 0,
  location: '',
  description: '',
})

const rules = reactive({
  examName: [{ required: true, message: '请输入考试名称', trigger: 'blur' }],
  courseId: [{ required: true, message: '请选择课程', trigger: 'blur' }],
  examDate: [{ required: true, message: '请输入考试时间', trigger: 'blur' }],
  duration: [{ required: true, message: '请输入考试时长', trigger: 'blur' }],
  location: [{ required: true, message: '请输入考试地点', trigger: 'blur' }],
})

// 添加菜单方法，id为 0则为添加根菜单
const dialogTitle = ref('新增考试')
const isEdit = ref(false)

const getExamInfoPage = async () => {
  loading.value = true
  try {
    const { data } = await reqGetAllExamByAdmin(examPageParmas)
    examDatas.value = data.list
    total.value = data.total
  } catch (error) {
    if (error instanceof Error) {
      ElMessage.error(error.message)
    }
  } finally {
    loading.value = false
  }
}

const getSemesterOption = async () => {
  try {
    const { data } = await reqGetSemesterOption()
    semesterOptions.value = data
  } catch (error) {
    if (error instanceof Error) {
      ElMessage.error(error.message)
    }
  }
}

const indexMethod = (index: number) => {
  return index + (examPageParmas.pageNum - 1) * examPageParmas.pageSize + 1
}

const deleteExamById = async (id: number) => {
  try {
    const { message } = await reqDeleteExamById(id)
    ElMessage.success(message)
    await getExamInfoPage()
  } catch (error) {
    ElMessage.error((error as Error).message)
  }
}

const addExam = async () => {
  try {
    const { message } = await reqAddExam(examForm)
    ElMessage.success(message)
    examForm = {
      examId: 0,
      examName: '',
      courseId: 0,
      examDate: '',
      duration: 0,
      location: '',
      description: '',
    }
    await getExamInfoPage()
  } catch (error) {
    ElMessage.error((error as Error).message)
  }
}

const updateExam = async () => {
  try {
    const { message } = await reqUpdateExam(examForm)
    ElMessage.success(message)
    await getExamInfoPage()
  } catch (error) {
    ElMessage.error((error as Error).message)
  }
}

const formConfirm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid) => {
    if (valid) {
      if (isEdit.value) {
        updateExam()
      } else {
        addExam()
      }
      dialogFormVisible.value = false
    }
  })
}

const openAddDialog = () => {
  isEdit.value = false
  if (examForm.examId !== 0) {
    examForm = {
      examId: 0,
      examName: '',
      courseId: 0,
      examDate: '',
      duration: 0,
      location: '',
      description: '',
    }
  }
  dialogTitle.value = '新增考试'
  dialogFormVisible.value = true
}
// 修改菜单方法
const openEditDialog = async (data: ExamType) => {
  isEdit.value = true
  dialogTitle.value = '编辑考试'
  examForm.examId = data.examId
  examForm.examName = data.examName
  examForm.courseId = data.courseId
  examForm.examDate = data.examDate
  examForm.duration = data.duration
  examForm.location = data.location
  examForm.description = data.description
  dialogFormVisible.value = true
}

const handleSizeChange = (val: number) => {
  getExamInfoPage()
}
const handleCurrentChange = (val: number) => {
  getExamInfoPage()
}
</script>
<style scoped lang="scss">
.exam_box {
  padding: 24px;

  .exam_addbtn {
    margin-bottom: 12px;
    display: flex;
    align-items: center;
  }
}
</style>
